package com.apes.scm.pur.priceChange;

import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.soe.annotations.State;
import com.apes.framework.plugin.soe.annotations.States;
import com.apes.framework.plugin.soe.metadata.BusinessAttributeValue;
import com.apes.framework.util.ApesConst;
import com.apes.framework.util.JpaUtil;
import com.apes.scm.account.account.model.Cooperation;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.service.PartyRoleService;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = PriceChangePlatform.CONST_TABLE_NAME)
public class PriceChangePlatform extends Model implements Cloneable {
    public static final String CONST_TABLE_NAME = "pur_price_change_platform";

    @Id
    @Column(name = "id", length = 32)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "平台采购变价单", padding = 4, prefix = "PB%(yy)%(month)", useDateRange = true)
    @Comment("变价单号")
    private String id;

//    @Comment("变价类型")
//    @ManyToOne(fetch = FetchType.LAZY)
//    @JoinColumn(name = "price_change_type", referencedColumnName = "id")
//    private Enumeration priceChangeType;

//    @NotNull
//    @ManyToOne(fetch = FetchType.LAZY)
//    @JoinColumn(name = "company_id", referencedColumnName = "id", nullable = true)
//    @Comment("公司编码")
//    private PartyRole company;

//    @NotNull
//    @ManyToOne(fetch = FetchType.LAZY)
//    @JoinColumn(name = "contract_id", referencedColumnName = "id", nullable = true)
//    @Comment("合同号")
//    private Contract contract;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "cooperation_id", referencedColumnName = "id")
    @Comment("合作方式编码")
    private Cooperation cooperation;

//    @NotNull
//    @ManyToOne(fetch = FetchType.LAZY)
//    @JoinColumn(name = "dept_id", referencedColumnName = "id", nullable = false)
//    @Comment("部门编码")
//    private Dept dept; //部门

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "supplier_id", referencedColumnName = "id", nullable = false)
    @Comment("供应商编码")
    private PartyRole supplier;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "clerk_id", referencedColumnName = "id", updatable = false)
    @Comment("业务员编码")
    private PartyRole clerk;

    @States(name = "库存方式", values = {
            @State(id = PriceChangeMode.PCM_STOCK_FIRST, name = "库存优先"),
            @State(id = PriceChangeMode.PCM_SALES_FIRST, name = "销售优先")})
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "price_change_mode", referencedColumnName = "id", nullable = false)
    private BusinessAttributeValue priceChangeMode;

    @Column(name = "source", length = 30)
    @Comment("上游单据")
    private String source;

    @Column(name = "source_business_type", length = 32)
    @Comment("上游单据类型")
    private String sourceBusinessType;

    @Column(name = "source_business_type_name", length = 64)
    @Comment("来源单据类型名称")
    private String sourceBusinessTypeName;

    @Column(name = "tax_amt", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("税金")
    private double taxAmt = 0;

    @Column(name = "amt_Without_tax", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("不含税金额")
    private double amtWithoutTax = 0;

    @Column(name = "amt_With_tax", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("含税金额")
    private double amtWithTax = 0;

    @Column(name = "amt_change_sales", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("变库存金额")
    private double amtChangeBalanceQty = 0;

    @Column(name = "note", length = 250)
    @Comment("备注")
    private String note;

    @Column(name = "confirmation_img", length = 250)
    @Comment("确认函照片")
    private String confirmationImg;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "approve_uid", referencedColumnName = "id")
    @Comment("审批人")
    private PartyRole approveUid;

    @Column(name = "approve_date")
    @Comment("审批日期")
    private Date approveDate; //审批日期

    @States(name = "单据状态", values = {
            @State(id = "sent", name = "创建"),
            @State(id = "delete", name = "删除"),
            @State(id = "done", name = "已审核")})
    @Column(name = "state", length = 10, nullable = false)
    private String state;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "delete_uid", referencedColumnName = "id")
    @Comment("删除人")
    private PartyRole deleteUid;

    @Column(name = "delete_date")
    @Comment("删除日期")
    private Date deleteDate;

    @OneToMany(mappedBy = "priceChangePlatform", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<PriceChangePlatformItem> priceChangeItemPlatforms = new ArrayList<>(); //订单行

    public List<PriceChangePlatformItem> getPriceChangeItemPlatforms() {
        for (PriceChangePlatformItem item : priceChangeItemPlatforms) {
            item.setPriceChangePlatform(this);
        }
        return priceChangeItemPlatforms;
    }

    public void computeAmt() {
        amtWithoutTax = 0;
        taxAmt = 0;
        amtChangeBalanceQty = 0;
        for (PriceChangePlatformItem item : priceChangeItemPlatforms) {
            if (item.getProductUomQty() <= 0) throw new RuntimeException("商品"+ item.getProduct().getId() +"变价数量必须大于0！");
            if (item.getNewPrice() <= 0) throw new RuntimeException("单价不能等于 或 小于 0！");
            item.computeAmt();
            amtWithoutTax += item.getAmtWithoutTax();
            taxAmt += item.getTaxAmt();
            amtChangeBalanceQty += item.getChangeSalesQty()*(item.getNewPrice()-item.getOldPrice());
        }
        amtWithTax = amtWithoutTax + taxAmt;
    }

    @Override
    protected Object clone() {
        PriceChangePlatform priceChangePlatform = null;
        try {
            priceChangePlatform = (PriceChangePlatform) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return priceChangePlatform;
    }

    @Transient
    private PartyRole createUid;

    public PartyRole getCreateUid(){
        if(getCreator()==null) return null;
        createUid = (PartyRole) JpaUtil.getImplementation(SpringManager.getBean(PartyRoleService.class).findByOrigin(getCreator()));
        return createUid;
    }

}
